package com.msos.servlet.loginServlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.msos.model.respBean.RespBean;
import com.msos.service.ManagerService.ManagerService;
import com.msos.service.customerService.CustomerService;
import com.msos.utils.CommonsUtils;
import com.msos.utils.VerificationCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName: LoginServlet
 * @Description: TODO
 * @Author: hsx
 * @Date: 2022/4/12 16:52
 * @Version: v1.0
 */
@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    CustomerService customerService = new CustomerService();
    ManagerService managerService =  new ManagerService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        if("vcode".equals(action)){
            //开始获取验证码
            VerificationCode vc = new VerificationCode();
            //获取验证码的图片
            BufferedImage image = vc.getImage();
            //获取验证码的文本
            String text = vc.getText();
            //将验证码文本存入session
            HttpSession session = req.getSession();
            session.setAttribute("vcode",text);
            //把验证码放到浏览器上展示
            VerificationCode.output(image,resp.getOutputStream());
        }else {
            //服务端跳转回登录页面
            req.getRequestDispatcher("/WEB-INF/jsp/login/login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        String role = req.getParameter("role");
        Integer rs = customerService.login(phone, password, req);
        RespBean respBean = null;
        if(rs == CommonsUtils.LOGIN_SUCCESS){
            respBean = RespBean.ok(role);
        }else if(rs == CommonsUtils.BAD_VCODE){
            respBean = RespBean.error("验证码错误");
        }else if(rs == CommonsUtils.USER_BLOCKED){
            respBean = RespBean.error("用户被封禁");
        }else if(rs == CommonsUtils.USER_NOTFOUND_OR_PASSWORD_BAD){
            respBean = RespBean.error("账户或者密码错误");
        }else if(rs == CommonsUtils.ROLE_ERROR){
            respBean = RespBean.error("你没有资格！正因为如此，你没有资格，没有资格啊！");
        }
        else {
            respBean = RespBean.error("登陆失败");
        }
        resp.setContentType("application/json;charset=utf-8");
        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(respBean);
        resp.getWriter().write(json);
    }
}
